<template>
  <!-- 标题栏 -->
  <div class="page-header">
    <div class="header-left">
      <el-icon class="header-icon"><Grid /></el-icon>
      <span class="header-title">医院列表</span>
    </div>
    <div class="header-right">
      <el-button type="primary" :icon="Plus" @click="onAddHospital">新增医院</el-button>
    </div>
  </div>

<el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="标题">
      <el-input v-model="formInline.name" placeholder="请输入标题或者关键字" clearable />
    </el-form-item>

    <el-form-item label="省份">
      <el-select v-model="formInline.province" placeholder="请选择省份" clearable @change="onProvinceChange">
        <el-option
          v-for="province in provinceList"
          :key="province.value"
          :label="province.label"
          :value="province.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="城市">
      <el-select v-model="formInline.city" placeholder="请选择城市" clearable :disabled="!formInline.province">
        <el-option
          v-for="city in cityList"
          :key="city.value"
          :label="city.label"
          :value="city.value"
        />
      </el-select>
    </el-form-item>

   

    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
      <el-button @click="onReset">重置</el-button>
    </el-form-item>
  </el-form>

      <el-table :data="tableData" border style="width: 100%" ref="tableRef" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" type="index" label="序号"  />
    <el-table-column prop="name" label="医院名称"  />
    <el-table-column prop="coverImageUrl" label="列表图" width="180">
         <template v-slot="scope">
            <div class="table-image-container" @click="previewImage(scope.row.coverImageUrl)">
                <img 
                    class="table-image" 
                    :src="scope.row.coverImageUrl"
                    :alt="scope.row.name"
                    @error="handleImageError"
                />
            </div>
        </template>
    </el-table-column>
    <el-table-column prop="level" label="医院等级"  />
    <el-table-column prop="address" label="医院地址"  />
    <el-table-column prop="status" label="状态"  >
        <template v-slot="a">
            <el-tag type="primary" v-if="a.row.status===true">上架</el-tag>
            <el-tag type="danger" v-if="a.row.status===false">下架</el-tag>
        </template>
    </el-table-column>
    <el-table-column prop="createTime" label="上传时间"  >
        <template v-slot="a">
                <span>
                {{ moment(a.row.createTime || a.row.createdAt || a.row.uploadTime || a.row.startTime).format("YYYY-MM-DD HH:mm:ss") }}
                </span>
        </template>
    </el-table-column>
    <el-table-column prop="introduction" label="备注"  />
    <el-table-column  label="操作" width="280px">
        <template v-slot="a">
            <el-button type="info" @click="onViewHospitalDetail(a.row)">详情</el-button>
            <el-button @click="onEditHospital(a.row)">编辑</el-button>
            <el-button type="danger" @click="onDeleteHospital(a.row)">删除</el-button>
        </template>
    </el-table-column>
  </el-table>

    <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="formInline.pageIndex"
      v-model:page-size="formInline.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagin.totaleCount"
    />
  </div>

  <!-- 新增/编辑医院对话框 -->
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑医院' : '新增医院'" width="600px" :before-close="handleClose">
    <el-form :model="hospitalForm" :rules="rules" ref="hospitalFormRef" label-width="100px">
      <el-form-item label="医院名称" prop="name" required>
        <el-input v-model="hospitalForm.name" placeholder="请输入..." clearable />
      </el-form-item>

      <!-- 轮播图上传 -->
      <el-form-item label="轮播图" prop="coverImageUrl" required>
                 <el-upload
             class="avatar-uploader"
             action="#"
             :show-file-list="false"
             :on-success="handleAvatarSuccess"
             :before-upload="beforeAvatarUpload"
             :http-request="customUpload"
             :auto-upload="true"
         >
             <img v-if="hospitalForm.coverImageUrl" :src="hospitalForm.coverImageUrl" class="avatar" />
             <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
         </el-upload>
      </el-form-item>

      <el-form-item label="是否推荐" prop="isRecommended" required>
        <el-radio-group v-model="hospitalForm.status">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="医生人数" prop="doctorCount">
        <el-input v-model="hospitalForm.doctorNumber" placeholder="请输入..." clearable />
      </el-form-item>

      <el-form-item label="科室数" prop="departmentCount">
        <el-input v-model="hospitalForm.departmentsNumber" placeholder="请输入..." clearable />
      </el-form-item>

      <el-form-item label="医院科室" prop="departments">
        <div class="department-selection">
          <div class="department-left">
            <el-checkbox-group v-model="hospitalForm.departments">
              <div v-for="department in departmentList" :key="department.values" class="department-group">
                <!-- 一级科室 -->
                <div class="department-primary">
                  <div class="department-primary-header" @click="toggleDepartment(department.values)">
                    <el-checkbox 
                      :label="department.label" 
                      :value="department.label"
                      @click.stop
                    >
                      {{ department.label }}
                    </el-checkbox>
                    <el-icon class="expand-icon" v-if="department.children && department.children.length > 0">
                      <ArrowDown v-if="!expandedDepartments.has(department.values)" />
                      <ArrowUp v-else />
                    </el-icon>
                  </div>
                  
                  <!-- 二级科室 -->
                  <div 
                    v-if="department.children && department.children.length > 0 && expandedDepartments.has(department.values)" 
                    class="department-secondary"
                  >
                    <div class="department-row">
                      <el-checkbox 
                        v-for="subDepartment in department.children" 
                        :key="subDepartment.values"
                        :label="subDepartment.label"
                        :value="subDepartment.label"
                      >
                        {{ subDepartment.label }}
                      </el-checkbox>
                    </div>
                  </div>
                </div>
              </div>
            </el-checkbox-group>
          </div>
          <div class="department-arrow">
            <el-icon><ArrowRight /></el-icon>
          </div>
          <div class="department-right">
            <el-input
              v-model="hospitalForm.selectedDepartments"
              type="textarea"
              :rows="6"
              placeholder="已选择的科室将显示在这里"
              readonly
            />
          </div>
        </div>
      </el-form-item>

      <el-form-item label="详细地址" prop="address" required>
        <el-input v-model="hospitalForm.address" placeholder="请输入..." clearable />
      </el-form-item>

      <el-form-item label="医院电话" prop="phone" required>
        <el-input v-model="hospitalForm.phone" placeholder="请输入..." clearable />
      </el-form-item>

      <el-form-item label="医院等级" prop="level" required>
        <el-input v-model="hospitalForm.level" placeholder="请输入..." clearable />
      </el-form-item>

      <el-form-item label="医院介绍" prop="introduction" required>
        <div class="editor-container">
          <div class="editor-toolbar">
           
          </div>
          <el-input
            v-model="hospitalForm.introduction"
            type="textarea"
            :rows="8"
            placeholder="请输入医院介绍..."
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 图片预览对话框 -->
  <el-dialog 
    v-model="imagePreviewVisible" 
    title="图片预览" 
    width="60%" 
    :before-close="() => imagePreviewVisible = false"
    class="image-preview-dialog"
  >
    <div class="image-preview-container">
      <img 
        :src="previewImageUrl" 
        alt="预览图片" 
        class="preview-image"
        @error="handleImageError"
      />
    </div>
  </el-dialog>

</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { showHospitals,uploadImage,getDepartments,addHospitals,updateHospitals,deleteHospitals } from '@/HTTPS/server';
import { useRouter } from 'vue-router';
import { reactive } from 'vue';
import moment from 'moment';
import { Grid, Plus, ArrowRight, ArrowDown, ArrowUp } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import type { UploadProps } from 'element-plus'

// 路由实例
const router = useRouter();

// 省份数据
const provinceList = ref([
  { value: '北京', label: '北京' },
  { value: '上海', label: '上海' },
  { value: '天津', label: '天津' },
  { value: '重庆', label: '重庆' },
  { value: '河北', label: '河北' },
  { value: '山西', label: '山西' },
  { value: '辽宁', label: '辽宁' },
  { value: '吉林', label: '吉林' },
  { value: '黑龙江', label: '黑龙江' },
  { value: '江苏', label: '江苏' },
  { value: '浙江', label: '浙江' },
  { value: '安徽', label: '安徽' },
  { value: '福建', label: '福建' },
  { value: '江西', label: '江西' },
  { value: '山东', label: '山东' },
  { value: '河南', label: '河南' },
  { value: '湖北', label: '湖北' },
  { value: '湖南', label: '湖南' },
  { value: '广东', label: '广东' },
  { value: '海南', label: '海南' },
  { value: '四川', label: '四川' },
  { value: '贵州', label: '贵州' },
  { value: '云南', label: '云南' },
  { value: '陕西', label: '陕西' },
  { value: '甘肃', label: '甘肃' },
  { value: '青海', label: '青海' },
  { value: '台湾', label: '台湾' },
  { value: '内蒙古', label: '内蒙古' },
  { value: '广西', label: '广西' },
  { value: '西藏', label: '西藏' },
  { value: '宁夏', label: '宁夏' },
  { value: '新疆', label: '新疆' },
  { value: '香港', label: '香港' },
  { value: '澳门', label: '澳门' }
]);

// 定义选项类型
interface OptionItem {
  value: string;
  label: string;
}

// 定义科室类型
interface Department {
  values: number;
  label: string;
  url: string | null;
  children: Department[];
}

// 城市数据
const cityList = ref<OptionItem[]>([]);

// 科室数据
const departmentList = ref<Department[]>([]);
// 展开的一级科室
const expandedDepartments = ref<Set<number>>(new Set());

// 省份对应的城市数据
const provinceCityMap: Record<string, OptionItem[]> = {
  '北京': [
    { value: '东城区', label: '东城区' },
    { value: '西城区', label: '西城区' },
    { value: '朝阳区', label: '朝阳区' },
    { value: '丰台区', label: '丰台区' },
    { value: '石景山区', label: '石景山区' },
    { value: '海淀区', label: '海淀区' },
    { value: '门头沟区', label: '门头沟区' },
    { value: '房山区', label: '房山区' },
    { value: '通州区', label: '通州区' },
    { value: '顺义区', label: '顺义区' },
    { value: '昌平区', label: '昌平区' },
    { value: '大兴区', label: '大兴区' },
    { value: '怀柔区', label: '怀柔区' },
    { value: '平谷区', label: '平谷区' },
    { value: '密云区', label: '密云区' },
    { value: '延庆区', label: '延庆区' }
  ],
  '上海': [
    { value: '黄浦区', label: '黄浦区' },
    { value: '徐汇区', label: '徐汇区' },
    { value: '长宁区', label: '长宁区' },
    { value: '静安区', label: '静安区' },
    { value: '普陀区', label: '普陀区' },
    { value: '虹口区', label: '虹口区' },
    { value: '杨浦区', label: '杨浦区' },
    { value: '闵行区', label: '闵行区' },
    { value: '宝山区', label: '宝山区' },
    { value: '嘉定区', label: '嘉定区' },
    { value: '浦东新区', label: '浦东新区' },
    { value: '金山区', label: '金山区' },
    { value: '松江区', label: '松江区' },
    { value: '青浦区', label: '青浦区' },
    { value: '奉贤区', label: '奉贤区' },
    { value: '崇明区', label: '崇明区' }
  ],
  '广东': [
    { value: '广州市', label: '广州市' },
    { value: '深圳市', label: '深圳市' },
    { value: '珠海市', label: '珠海市' },
    { value: '汕头市', label: '汕头市' },
    { value: '佛山市', label: '佛山市' },
    { value: '韶关市', label: '韶关市' },
    { value: '湛江市', label: '湛江市' },
    { value: '肇庆市', label: '肇庆市' },
    { value: '江门市', label: '江门市' },
    { value: '茂名市', label: '茂名市' },
    { value: '惠州市', label: '惠州市' },
    { value: '梅州市', label: '梅州市' },
    { value: '汕尾市', label: '汕尾市' },
    { value: '河源市', label: '河源市' },
    { value: '阳江市', label: '阳江市' },
    { value: '清远市', label: '清远市' },
    { value: '东莞市', label: '东莞市' },
    { value: '中山市', label: '中山市' },
    { value: '潮州市', label: '潮州市' },
    { value: '揭阳市', label: '揭阳市' },
    { value: '云浮市', label: '云浮市' }
  ],
  '江苏': [
    { value: '南京市', label: '南京市' },
    { value: '无锡市', label: '无锡市' },
    { value: '徐州市', label: '徐州市' },
    { value: '常州市', label: '常州市' },
    { value: '苏州市', label: '苏州市' },
    { value: '南通市', label: '南通市' },
    { value: '连云港市', label: '连云港市' },
    { value: '淮安市', label: '淮安市' },
    { value: '盐城市', label: '盐城市' },
    { value: '扬州市', label: '扬州市' },
    { value: '镇江市', label: '镇江市' },
    { value: '泰州市', label: '泰州市' },
    { value: '宿迁市', label: '宿迁市' }
  ],
  '浙江': [
    { value: '杭州市', label: '杭州市' },
    { value: '宁波市', label: '宁波市' },
    { value: '温州市', label: '温州市' },
    { value: '嘉兴市', label: '嘉兴市' },
    { value: '湖州市', label: '湖州市' },
    { value: '绍兴市', label: '绍兴市' },
    { value: '金华市', label: '金华市' },
    { value: '衢州市', label: '衢州市' },
    { value: '舟山市', label: '舟山市' },
    { value: '台州市', label: '台州市' },
    { value: '丽水市', label: '丽水市' }
  ]
  // 可以继续添加其他省份的城市数据
};

// 获取科室数据
const loadDepartments = () => {
    getDepartments().then(res => {
        console.log('科室数据:', res.data.data);
        if (res.data.code === 200 && res.data.data) {
            departmentList.value = res.data.data;
        }
    }).catch(error => {
        console.error('获取科室数据失败:', error);
        ElMessage.error('获取科室数据失败');
    });
}

onMounted(()=>{
    show();
    loadDepartments();
})


const formInline = reactive({
  name: '',
  province: '',
  city: '',
  address:"", // 保留用于组合省份+城市发送给后端
  pageIndex: 1,
  pageSize:10
  
})

// 省份变化处理
const onProvinceChange = (province: string) => {
  console.log('省份变化:', province);
  formInline.city = ''; // 清空城市选择
  if (province && provinceCityMap[province]) {
    cityList.value = provinceCityMap[province];
  } else {
    cityList.value = [];
  }
  // 更新address字段用于后端查询
  updateAddress();
};

// 更新地址字段
const updateAddress = () => {
  if (formInline.province && formInline.city) {
    formInline.address = `${formInline.province} ${formInline.city}`;
  } else if (formInline.province) {
    formInline.address = formInline.province;
  } else {
    formInline.address = '';
  }
};

// 监听城市变化
watch(() => formInline.city, () => {
  updateAddress();
});

const onSubmit = () => {
  console.log('submit!')
  formInline.pageIndex = 1; // 重置到第一页
  show();
}

//重置
const onReset = () => {
  console.log('reset!')
  // 重置查询条件
  formInline.name = '';
  formInline.province = '';
  formInline.city = '';
  formInline.address = '';
  formInline.pageIndex = 1;
  formInline.pageSize = 10;
  // 清空城市列表
  cityList.value = [];
  // 刷新列表
  show();
}

// 分页数据
const pagin = ref({
    totaleCount: 0,
    pageCount: 0,
})

// 监听分页参数变化
watch(formInline, () => {
    show();
}, { deep: true })

//显示
const tableData = ref([])
const show=()=>{
    showHospitals(formInline).then(res=>{
        console.log('API返回的数据:', res.data.data.list);
        tableData.value = res.data.data.list;
        pagin.value.pageCount = res.data.data.pageCount;
        pagin.value.totaleCount = res.data.data.totaleCount;
        // 清空选中状态
        selectedRows.value = [];
    })
}


// 表格选择相关
const tableRef = ref();
const selectedRows = ref<any[]>([]);

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection;
    console.log('当前选中的行:', selection);
}

// 对话框控制
const dialogVisible = ref(false);
const hospitalFormRef = ref();
const isEdit = ref(false);
const editingHospitalId = ref(null);

// 医院表单数据
const hospitalForm = reactive({
  name: '',
  coverImageUrl: '',
  doctorNumber: '',
  level:"",
  departmentsNumber: '',
  status:false,
  departments: [] as string[],
  selectedDepartments: '',
  address: '',
  phone: '',
  introduction: ''
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入医院名称', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入医院电话', trigger: 'blur' }
  ],
  introduction: [
    { required: true, message: '请输入医院介绍', trigger: 'blur' }
  ]
};

// 切换科室展开状态
const toggleDepartment = (departmentId: number) => {
    if (expandedDepartments.value.has(departmentId)) {
        expandedDepartments.value.delete(departmentId);
    } else {
        expandedDepartments.value.add(departmentId);
    }
}

// 监听科室选择变化
watch(() => hospitalForm.departments, (newVal) => {
  hospitalForm.selectedDepartments = newVal.join('、');
}, { deep: true });

// 新增医院
const onAddHospital = () => {
    console.log('新增医院');
    isEdit.value = false;
    editingHospitalId.value = null;
    resetForm();
    dialogVisible.value = true;
}

// 编辑医院
const onEditHospital = (hospital: any) => {
    console.log('编辑医院:', hospital);
    isEdit.value = true;
    editingHospitalId.value = hospital.id;
    
    // 数据反填
    hospitalForm.name = hospital.name || '';
    hospitalForm.level = hospital.level || '';
    hospitalForm.coverImageUrl = hospital.coverImageUrl || '';
    hospitalForm.status = hospital.status || false;
    hospitalForm.doctorNumber = hospital.doctorNumber || '';
    hospitalForm.departmentsNumber = hospital.departmentsNumber || '';
    hospitalForm.address = hospital.address || '';
    hospitalForm.phone = hospital.phone || '';
    hospitalForm.introduction = hospital.introduction || '';
    
    // 处理科室数据反填
    if (hospital.departmentsId) {
        // 如果departmentsId是数字，直接使用；如果是字符串，需要解析
        let departmentIds: number[] = [];
        if (typeof hospital.departmentsId === 'string') {
            departmentIds = hospital.departmentsId.split(',').map((id: string) => parseInt(id.trim())).filter((id: number) => !isNaN(id));
        } else if (typeof hospital.departmentsId === 'number') {
            departmentIds = [hospital.departmentsId];
        }
        
        const selectedDepartmentNames: string[] = [];
        
        departmentList.value.forEach(dept => {
            if (departmentIds.includes(dept.values)) {
                selectedDepartmentNames.push(dept.label);
            }
            if (dept.children && dept.children.length > 0) {
                dept.children.forEach(subDept => {
                    if (departmentIds.includes(subDept.values)) {
                        selectedDepartmentNames.push(subDept.label);
                    }
                });
            }
        });
        
        hospitalForm.departments = selectedDepartmentNames;
        hospitalForm.selectedDepartments = selectedDepartmentNames.join('、');
    } else {
        hospitalForm.departments = [];
        hospitalForm.selectedDepartments = '';
    }
    
    dialogVisible.value = true;
}

// 删除医院
const onDeleteHospital = (hospital: any) => {
    ElMessageBox.confirm(
        `确定要删除医院"${hospital.name}"吗？删除后不可恢复！`,
        '删除确认',
        {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger'
        }
    ).then(() => {
        // 用户确认删除
        const deleteData = {
            id: hospital.id
        };
        
        console.log('删除医院数据:', deleteData);
        
        deleteHospitals(deleteData)
            .then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message || '删除医院成功');
                    // 刷新列表
                    show();
                } else {
                    ElMessage.error(res.data.message || '删除医院失败');
                }
            })
            .catch(error => {
                ElMessage.error('删除医院失败');
                console.error('删除医院错误:', error);
            });
    }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消删除');
    });
}

// 查看医院详情
const onViewHospitalDetail = (hospital: any) => {
    console.log('查看医院详情:', hospital);
    // 跳转到医院详情页面，传递医院ID
    router.push({
        name: 'HospitalDetail',
        params: {
            id: hospital.id
        }
    });
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  // 重置编辑状态
  isEdit.value = false;
  editingHospitalId.value = null;
  // 重置表单
  resetForm();
}

// 重置表单
const resetForm = () => {
  hospitalForm.name = '';
  hospitalForm.level="";
  hospitalForm.coverImageUrl = '';
  hospitalForm.status = false;
  hospitalForm.doctorNumber = '';
  hospitalForm.departmentsNumber = '';
  hospitalForm.departments = [];
  hospitalForm.selectedDepartments = '';
  hospitalForm.address = '';
  hospitalForm.phone = '';
  hospitalForm.introduction = '';
  if (hospitalFormRef.value) {
    hospitalFormRef.value.clearValidate();
  }
}

// 提交表单
const handleSubmit = () => {
    // 构建提交数据
    const submitData: any = {
        name: hospitalForm.name,
        level: hospitalForm.level,
        address: hospitalForm.address,
        phone: hospitalForm.phone,
        introduction: hospitalForm.introduction,
        coverImageUrl: hospitalForm.coverImageUrl,
        status: hospitalForm.status,
        doctorNumber: parseInt(hospitalForm.doctorNumber) || 0,
        departmentsNumber: parseInt(hospitalForm.departmentsNumber) || 0,
        // 将选中的科室名称转换为科室ID，并转换为数字
        departmentsId: getDepartmentIdsAsNumber(hospitalForm.departments)
    };
    
    // 如果是编辑模式，添加ID
    if (isEdit.value && editingHospitalId.value) {
        submitData.id = parseInt(editingHospitalId.value);
    }
    
    console.log('提交的数据:', submitData);
    
    const apiCall = isEdit.value ? updateHospitals(submitData) : addHospitals(submitData);
    const actionText = isEdit.value ? '修改' : '新增';
    
    apiCall.then(res => {
        if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            dialogVisible.value = false;
            show();
        } else {
            ElMessage.error(res.data.message);
        }
    }).catch(error => {
        ElMessage.error(`${actionText}医院失败`);
        console.error(error);
    });
}

// 将科室名称转换为科室ID（字符串格式，用于显示）
const getDepartmentIds = (departmentNames: string[]) => {
    const ids: number[] = [];
    
    departmentList.value.forEach(dept => {
        if (departmentNames.includes(dept.label)) {
            ids.push(dept.values);
        }
        if (dept.children && dept.children.length > 0) {
            dept.children.forEach(subDept => {
                if (departmentNames.includes(subDept.label)) {
                    ids.push(subDept.values);
                }
            });
        }
    });
    
    return ids.join(',');
}

// 将科室名称转换为科室ID（数字格式，用于API提交）
const getDepartmentIdsAsNumber = (departmentNames: string[]) => {
    const ids: number[] = [];
    
    departmentList.value.forEach(dept => {
        if (departmentNames.includes(dept.label)) {
            ids.push(dept.values);
        }
        if (dept.children && dept.children.length > 0) {
            dept.children.forEach(subDept => {
                if (departmentNames.includes(subDept.label)) {
                    ids.push(subDept.values);
                }
            });
        }
    });
    
    // 返回第一个ID作为主科室ID，如果没有选择则返回0
    return ids.length > 0 ? ids[0] : 0;
}
// 自定义上传方法
const customUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    
    console.log('开始上传文件到MinIO:', file);
    
    let fileToUpload = file;
    
    // 如果图片大于1MB，进行压缩
    if (fileToUpload.size / 1024 / 1024 > 1) {
        try {
            fileToUpload = await compressImage(fileToUpload);
            console.log(`图片已压缩：${(file.size / 1024 / 1024).toFixed(2)}MB -> ${(fileToUpload.size / 1024 / 1024).toFixed(2)}MB`);
            ElMessage.success(`图片已自动压缩：${(file.size / 1024 / 1024).toFixed(2)}MB -> ${(fileToUpload.size / 1024 / 1024).toFixed(2)}MB`);
        } catch (error) {
            console.error('图片压缩失败:', error);
            ElMessage.warning('图片压缩失败，将使用原图上传');
        }
    }
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('file', fileToUpload);
    
    // 调用上传API
    uploadImage(formData)
        .then(res => {
            console.log('上传响应:', res);
            
            if (res.data.code === 200 || res.status === 200) {
                // 从响应中获取图片URL
                let coverImageUrl = res.data.data?.url || res.data.data?.coverImageUrl || res.data.data || res.data.url;
                
                // 确保URL是完整的
                if (coverImageUrl && !coverImageUrl.startsWith('http')) {
                    coverImageUrl = 'http://8.141.112.218:9000' + (coverImageUrl.startsWith('/') ? coverImageUrl : '/' + coverImageUrl);
                }
                
                console.log('处理后的图片URL:', coverImageUrl);
                hospitalForm.coverImageUrl = coverImageUrl;
                
                ElMessage.success('图片上传成功');
                onSuccess(res.data);
            } else {
                ElMessage.error('图片上传失败');
                onError(new Error('上传失败'));
            }
        })
        .catch(error => {
            console.error('上传错误:', error);
            ElMessage.error('图片上传失败');
            onError(error);
        });
}

const handleAvatarSuccess=(imgs:any) => {
    console.log('上传成功回调:', imgs);
    hospitalForm.coverImageUrl = imgs
}

// 图片预览功能
const imagePreviewVisible = ref(false);
const previewImageUrl = ref('');

const previewImage = (url: string) => {
    if (url) {
        previewImageUrl.value = url;
        imagePreviewVisible.value = true;
    }
};

// 图片加载错误处理
const handleImageError = (event: Event) => {
    const img = event.target as HTMLImageElement;
    img.src = ''; // 默认占位图
};

// 图片压缩函数
const compressImage = (file: File, maxWidth: number = 800, maxHeight: number = 600, quality: number = 0.8): Promise<File> => {
    return new Promise((resolve) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d')!;
        const img = new Image();
        
        img.onload = () => {
            // 计算压缩后的尺寸
            let { width, height } = img;
            
            if (width > height) {
                if (width > maxWidth) {
                    height = (height * maxWidth) / width;
                    width = maxWidth;
                }
            } else {
                if (height > maxHeight) {
                    width = (width * maxHeight) / height;
                    height = maxHeight;
                }
            }
            
            canvas.width = width;
            canvas.height = height;
            
            // 绘制压缩后的图片
            ctx.drawImage(img, 0, 0, width, height);
            
            // 转换为Blob
            canvas.toBlob((blob) => {
                if (blob) {
                    const compressedFile = new File([blob], file.name, {
                        type: file.type,
                        lastModified: Date.now()
                    });
                    resolve(compressedFile);
                } else {
                    resolve(file);
                }
            }, file.type, quality);
        };
        
        img.src = URL.createObjectURL(file);
    });
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = async (rawFile) => {
    const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/jpg';
    const isLt5M = rawFile.size / 1024 / 1024 < 5; // 放宽到5MB，因为我们会压缩

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!');
        return false;
    }
    if (!isLt5M) {
        ElMessage.error('上传图片大小不能超过 5MB!');
        return false;
    }
    
    // 如果图片大于1MB，进行压缩
    if (rawFile.size / 1024 / 1024 > 1) {
        try {
            const compressedFile = await compressImage(rawFile);
            console.log(`图片压缩：${(rawFile.size / 1024 / 1024).toFixed(2)}MB -> ${(compressedFile.size / 1024 / 1024).toFixed(2)}MB`);
            // 替换原文件
            Object.defineProperty(rawFile, 'size', { value: compressedFile.size });
            Object.defineProperty(rawFile, 'stream', { value: () => compressedFile.stream() });
            Object.defineProperty(rawFile, 'arrayBuffer', { value: () => compressedFile.arrayBuffer() });
        } catch (error) {
            console.error('图片压缩失败:', error);
            ElMessage.warning('图片压缩失败，将使用原图上传');
        }
    }
    
    return true;
}


</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-icon {
  font-size: 18px;
  color: #606266;
  margin-right: 8px;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
}

.demo-form-inline {
  margin-bottom: 20px;
}

.demo-pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.upload-area {
  width: 120px;
  height: 90px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #c0c4cc;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 12px;
  color: #999;
  text-align: center;
  line-height: 1.2;
}

.uploaded-image {
  width: 120px;
  height: 90px;
  object-fit: cover;
  border-radius: 6px;
}

.department-selection {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  width: 100%;
}

.department-left {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  min-height: 150px;
}

.department-row {
  margin-bottom: 10px;
  display: flex;
  gap: 15px;
}

.department-row:last-child {
  margin-bottom: 0;
}

/* 动态科室样式 */
.department-group {
  margin-bottom: 15px;
}

.department-group:last-child {
  margin-bottom: 0;
}

.department-primary {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.department-primary-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #f8f9fa;
  cursor: pointer;
  transition: background-color 0.3s;
}

.department-primary-header:hover {
  background-color: #e9ecef;
}

.expand-icon {
  font-size: 14px;
  color: #909399;
  transition: transform 0.3s;
}

.department-secondary {
  padding: 10px 15px;
  background-color: #ffffff;
  border-top: 1px solid #e4e7ed;
}

.department-secondary .department-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 0;
}

.department-secondary .el-checkbox {
  margin-right: 0;
}

.department-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 60px;
}

.department-arrow .el-icon {
  font-size: 20px;
  color: #c0c4cc;
}

.department-right {
  flex: 1;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  background-color: #f5f7fa;
  padding: 8px 12px;
  border-bottom: 1px solid #dcdfe6;
}

.editor-toolbar .el-button-group {
  display: flex;
  gap: 2px;
}

.editor-container .el-textarea {
  border: none;
}

.editor-container .el-textarea__inner {
  border: none;
  border-radius: 0;
  box-shadow: none;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格图片样式 */
.table-image-container {
  width: 150px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
}

.table-image-container:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  transform: scale(1.02);
}

.table-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.table-image:hover {
  transform: scale(1.05);
}

/* 上传组件样式 */
.avatar-uploader .avatar {
  width: 200px;
  height: 150px;
  display: block;
  object-fit: cover;
  border-radius: 8px;
}

.avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  width: 200px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 150px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 图片预览对话框样式 */
.image-preview-dialog .el-dialog__body {
  padding: 20px;
  text-align: center;
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .table-image-container {
    width: 100px;
    height: 80px;
  }
  
  .avatar-uploader .avatar,
  .avatar-uploader .el-upload,
  .el-icon.avatar-uploader-icon {
    width: 150px;
    height: 120px;
  }
  
  .image-preview-dialog {
    width: 90% !important;
  }
  
  .preview-image {
    max-height: 50vh;
  }
}

@media (max-width: 480px) {
  .table-image-container {
    width: 80px;
    height: 60px;
  }
  
  .avatar-uploader .avatar,
  .avatar-uploader .el-upload,
  .el-icon.avatar-uploader-icon {
    width: 120px;
    height: 100px;
  }
}
</style>